const express = require('express')
const user = express.Router()
// 导入multer包,操作上传来的图片
const multer = require('multer')
// 导入path,用来操作路径
const path = require('path')
// 导入fs,用来操作文件
const fs = require('fs')
const pool = require('../pool')
// 指定上传过来图片的保存路径
const upload = multer({ dest: '../public/img' })


// 用户注册时上传头像接口
user.post('/register/avatar', upload.single('avatar'), (req, res) => {
    console.log(req.file);
    // 保存传递过来的文件
    let obj = req.file
    // 保存图片的后缀名  xxx.jpg
    let originName = obj.originalname
    // 保存图片原先的路径,这个不带后缀
    let originPath = obj.path
    // 得到后缀 .jpg
    let extName = path.extname(originName)
    // 拼接得到最新的路径
    let newName = originPath + extName
    // 将文件重命名
    fs.renameSync(originPath, newName)
    // 拼接得到存入数据库的路径,也就是前端获取时的路径
    let str = obj.filename + extName
    str = `/img\/${str}`
    // 获取当前时间戳
    // let time = Date.now()
    // let data = {
    //     uname: req.body.uname,
    //     upwd: req.body.upwd,
    //     phone: req.body.phone,
    //     avatar: str,
    //     user_name: req.body.user_name,
    //     gender: req.body.gender,
    //     create_time: time
    // }
    res.send(str)

})
//用户注册接口
user.post('/register', (req, res) => {
    req.body.create_time = Date.now()
    console.log(req.body);
    let data = req.body
    let url = 'INSERT INTO hd_user SET ?'
    pool.query(url, [data], (err, result) => {
        if (err) throw err
        if (result.affectedRows == 0) res.send({ code: 300, msg: '注册失败' })
        res.send({ code: 200, msg: '注册成功' })
    })
})
// 登录路由
user.post('/login', (req, res) => {
    //获取用户名
    let uname = req.body.uname;
    //获取密码
    let upwd = req.body.upwd;
    //登录时间(当前日期时间戳)
    let login_time = Date.now();
    //登录状态(0未登录，1登录)
    let state = 1;
    // SQL语句
    let sql = 'select uid,uname,upwd,user_name,avatar,state,permissions from hd_user where uname=? and upwd=?';
    // 执行SQL语句
    pool.query(sql, [uname, upwd], (error, results) => {
        if (error) nexterror;
        if (results.length == 0) {
            //登录失败
            res.send({ message: '登录失败...', code: 201 });
        } else {
            //登录成功
            res.send({ message: 'ok', code: 200, results: results[0] });
            //登录成功就插入当前日期时间戳
            sql = 'update hd_user set login_time=?,state=? where uname=?'
            pool.query(sql, [login_time, state, uname], (error, results) => {
                if (error) nexterror;
            })
        }
    });
});

module.exports = user